<template>
  <div class="app-container">
    <el-row>
      <el-col :xs="24" :sm="24" :lg="{span: 16, offset: 4}">
        <el-card>
          <div class="avatar-wrapper" @click="imagecropperShow=true">
            <img v-if="avatar" :src="avatar" class="user-avatar">
            <img v-else src="@/assets/avatar.jpg" class="user-avatar">
          </div>
          <div class="form-wrapper">
            <el-form ref="dataForm" :label-width="formLabelWidth" :rules="rules" :model="form">
              <el-form-item label="手机号" prop="mobile">
                <span v-if="form.mobile" style="color: #606266;margin-left: 10px"> {{ form.mobile }} </span>
                <el-button v-if="form.mobile" type="text" size="small" style="margin-left: 10px" @click="handleChangeMobile">修改</el-button>
                <el-button v-else type="text" size="small" style="margin-left: 10px" @click="handleBindMobile">绑定手机</el-button>
              </el-form-item>
              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="form.nickname" auto-complete="off"/>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" auto-complete="off"/>
              </el-form-item>
            </el-form>
            <div slot="footer" class="form-footer">
              <el-button @click="handleCancel">取 消</el-button>
              <el-button type="primary" @click.native.prevent="submitForm">修改</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!--绑定手机-->
    <el-dialog :visible.sync="bindFormVisible" :before-close="handleCancelBind" title="绑定手机" center width="40%">
      <el-form ref="bindForm" :label-width="formLabelWidth" :rules="bindRules" :model="bindForm">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="bindForm.mobile" auto-complete="off">
            <el-button slot="append" :disabled="!sendVerifyCode" @click="handleVerify('bindForm', 'mobile', bindForm.mobile, 4)">{{ btnmsg }}</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="verifyCode">
          <el-input v-model="bindForm.verifyCode" auto-complete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelBind">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitBindForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--更新手机-->
    <el-dialog :visible.sync="changeDialogVisible" :before-close="handleCancelChange" title="更改手机" center width="40%">
      <el-steps :active="active" class="mobile-step" process-status="finish" finish-status="success">
        <el-step icon="el-icon-mobile-phone" title="验证"/>
        <el-step icon="el-icon-edit-outline" title="修改"/>
        <el-step icon="el-icon-circle-check-outline" title="完成"/>
      </el-steps>
      <div class="step-body">
        <el-form v-if="active === 0" ref="oldForm" :label-width="formLabelWidth" :rules="oldRules" :model="oldForm">
          <el-form-item label="原手机号" prop="oldMobile">
            <el-input v-model="oldForm.oldMobile" auto-complete="off">
              <el-button slot="append" :disabled="!sendVerifyCode" @click="handleVerify('oldForm', 'oldMobile', oldForm.oldMobile, 5)">{{ btnmsg }}</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="oldVerifyCode">
            <el-input v-model="oldForm.oldVerifyCode" auto-complete="off"/>
          </el-form-item>
        </el-form>
        <el-form v-show="active === 1" ref="newForm" :label-width="formLabelWidth" :rules="newRules" :model="newForm">
          <el-form-item label="新手机号" prop="mobile">
            <el-input v-model="newForm.mobile" auto-complete="off">
              <el-button slot="append" :disabled="!sendVerifyCode" @click="handleVerify('newForm', 'mobile', newForm.mobile, 5)">{{ btnmsg }}</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="verifyCode">
            <el-input v-model="newForm.verifyCode" auto-complete="off"/>
          </el-form-item>
        </el-form>
        <div v-if="active === 2" class="succ-wrapper" >
          <span>更改成功！</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="active === 0" type="primary" @click="next">下一步</el-button>
        <el-button v-if="active === 1" @click="handleCancelChange">取 消</el-button>
        <el-button v-if="active === 1" type="primary" @click.native.prevent="submitChangeForm">确 认</el-button>
        <el-button v-if="active === 2" @click="handleClose">关 闭</el-button>
      </div>
    </el-dialog>
    <image-cropper
      v-show="imagecropperShow"
      :width="300"
      :height="300"
      :key="imagecropperKey"
      :url="url"
      lang-type="zh"
      @close="close"
      @crop-upload-success="cropSuccess"/>
  </div>
</template>

<script>
import ImageCropper from '@/components/ImageCropper'
import { mapGetters } from 'vuex'
import { isvalidateMobile, isvalidateEmail } from '@/utils/validate'
import { getInfo, changeInfo, bindMobile, changeMobile, getVerifycode, checkVerifycode } from '@/api/user'

export default {
  name: 'User',
  components: { ImageCropper },
  data() {
    /* 校验合法手机号 */
    const validateMobile = (rule, value, callback) => {
      if (!isvalidateMobile(value)) {
        callback(new Error('请输入正确手机号码'))
      } else {
        callback()
      }
    }
    /* 校验合法邮箱 */
    const validateEmail = (rule, value, callback) => {
      if (value && !isvalidateEmail(value)) {
        callback(new Error('请输入正确邮箱'))
      } else {
        callback()
      }
    }
    return {
      imagecropperShow: false,
      imagecropperKey: 0,
      url: process.env.BASE_API + '/mgr/user/avatar',
      data: {},
      bindFormVisible: false,
      sendVerifyCode: true,
      btnmsg: '点击获取短信验证码',
      count: 60,
      form: {
        mobile: '',
        nickname: '',
        email: ''
      },
      rules: {
        nickname: [{ max: 32, message: '昵称长度不超过32个字符', trigger: 'blur' }],
        email: [{ validator: validateEmail, trigger: 'blur' }]
      },
      bindForm: {
        mobile: '',
        verifyCode: ''
      },
      bindRules: {
        mobile: [{ required: true, message: '请输入手机号', trigger: 'change' }, { validator: validateMobile, trigger: 'change' }],
        verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      formLabelWidth: '20%',
      timer: null,
      active: 0,
      changeDialogVisible: false,
      oldForm: {
        oldMobile: '',
        oldVerifyCode: ''
      },
      newForm: {
        mobile: '',
        verifyCode: ''
      },
      oldRules: {
        oldVerifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      newRules: {
        mobile: [{ required: true, message: '请输入手机号', trigger: 'change' }, { validator: validateMobile, trigger: 'change' }],
        verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'avatar'
    ])
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      getInfo(this.listQuery).then(response => {
        if (response) {
          this.data = response
          this.form = JSON.parse(JSON.stringify(response))
          this.handleCancel()
        }
      })
    },
    handleCancel() {
      this.form = JSON.parse(JSON.stringify(this.data))
      this.$refs['dataForm'].clearValidate()
    },
    resetVerifyCode() {
      this.sendVerifyCode = true
      this.btnmsg = '点击获取短信验证码'
      this.count = 60
      clearInterval(this.timer)
    },
    handleVerify(form, prop, mobile, type) {
      this.$refs[form].validateField(prop, (msg) => {
        if (!msg) {
          getVerifycode({ 'mobile': mobile, 'type': type }).then(() => {
            this.timer = setInterval(() => {
              console.log(this.timer)
              this.count--
              this.btnmsg = this.count + '秒后重新发送'
              this.sendVerifyCode = false
              if (this.count <= 0) {
                this.resetVerifyCode()
              }
            }, 1000)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitForm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          changeInfo(this.form).then(() => {
            this.actiniaSucc('修改信息成功')
            this.$refs['dataForm'].clearValidate()
            this.fetchData()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetBindForm() {
      this.bindForm = {
        mobile: '',
        verifyCode: ''
      }
    },
    handleBindMobile() {
      this.resetBindForm()
      this.resetVerifyCode()
      this.bindFormVisible = true
      this.$nextTick(() => {
        this.$refs['bindForm'].clearValidate()
      })
    },
    handleCancelBind() {
      this.resetVerifyCode()
      this.bindFormVisible = false
    },
    submitBindForm() {
      this.$refs['bindForm'].validate((valid) => {
        if (valid) {
          bindMobile(this.bindForm).then(() => {
            this.actiniaSucc('绑定手机成功')
            this.bindFormVisible = false
            this.resetVerifyCode()
            this.fetchData()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetChangeForm() {
      this.oldForm = {
        oldMobile: this.data.mobile,
        oldVerifyCode: ''
      }
      this.newForm = {
        mobile: '',
        verifyCode: ''
      }
    },
    handleChangeMobile() {
      this.resetChangeForm()
      this.resetVerifyCode()
      this.changeDialogVisible = true
      this.$nextTick(() => {
        this.$refs['oldForm'].clearValidate()
      })
    },
    handleCancelChange() {
      this.resetVerifyCode()
      this.active = 0
      this.changeDialogVisible = false
    },
    next() {
      this.$refs['oldForm'].validate((valid) => {
        if (valid) {
          checkVerifycode({ 'mobile': this.oldForm.oldMobile, 'verifyCode': this.oldForm.oldVerifyCode }).then(() => {
            this.resetVerifyCode()
            if (this.active++ > 2) this.active = 0
            this.$nextTick(() => {
              this.$refs['newForm'].clearValidate()
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitChangeForm() {
      this.$refs['newForm'].validate((valid) => {
        if (valid) {
          changeMobile(Object.assign({}, this.oldForm, this.newForm)).then(() => {
            this.resetVerifyCode()
            if (this.active++ > 2) this.active = 0
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleClose() {
      this.changeDialogVisible = false
      this.active = 0
      this.fetchData()
    },
    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      if (resData.avatar) {
        this.$store.dispatch('ChangeAvatar', resData.avatar).then(() => {
          this.actiniaSucc('头像上传成功')
        })
      } else {
        this.$message({
          message: '头像上传失败',
          type: 'error'
        })
      }
    },
    close() {
      this.imagecropperShow = false
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .avatar-wrapper {
    text-align: center;
    margin: 0 auto 20px;
    .user-avatar{
      width: 150px;
      height: 150px;
      border-radius: 50%;
      cursor:pointer;
    }
  }

  .form-wrapper {
    width: 60%;
    margin: 0 auto;
    .form-footer {
      text-align: center;
      margin: 100px 0;
    }
  }

  .mobile-step {
    margin: 0 20px 50px;
  }

  .step-body {
    height: 150px;
  }

  .succ-wrapper {
    text-align: center;
    font-size: 20px
  }
</style>

